package com.woniuxy.rabbitmq79.direct;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author zhangyong
 * @Date 2021/8/11 0011下午 3:03
 */
public class DirectConsumerCD {
    public static void main(String[] args) throws Exception {
        //1.创建连接工厂：创建连接
        ConnectionFactory factory = new ConnectionFactory();

        //2.设置连接参数
        factory.setHost("localhost");   //mq的ip
        factory.setUsername("guest");   //账号
        factory.setPassword("guest");   //密码
        factory.setVirtualHost("/");    //设置虚拟主机 不设置默认/

        //3.创建连接
        Connection connection = factory.newConnection();     //IO异常

        //4.创建通道
        Channel channel = connection.createChannel();

        //创建或者获取交换机
        channel.exchangeDeclare("direct_exchange", "direct");

        //随机获取消息队列
        String queue = channel.queueDeclare().getQueue();

        //绑定交换机、队列 将队列绑定到交换机
        channel.queueBind(queue, "direct_exchange", "chengdu");

        //创建消费者对象
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                String message = new String(body, "UTF-8");

                System.out.println(message);

            }
        };
        //接收消息
        channel.basicConsume(queue, true, consumer);
    }
}
